package com.xuxueli.applyModules.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class ResponseUtil {

    public static void responseWrite(Object result, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            out.write(JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue));
            out.flush();
        } catch (IOException e) {
            log.error("文件流写失败", e);
        }
    }

    public static void responseWrite(byte[] bodyBytes, HttpServletResponse response) {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        try (ByteArrayInputStream in = new ByteArrayInputStream(bodyBytes); OutputStream out = response
            .getOutputStream()) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void responseWrite(InputStream in, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
